package com.mical.demo.config;

import com.mical.demo.security.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class TokenExpirationListener implements ApplicationListener<AuthenticationSuccessEvent> {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        try {
            // 每次认证成功时检查并清理过期Token
            String username = event.getAuthentication().getName();
            Set<String> tokens = redisTemplate.opsForSet().members("user:tokens:" + username);

            if (tokens != null) {
                tokens.forEach(token -> {
                    try {
                        if (jwtTokenUtil.isTokenExpired(token)) {
                            redisTemplate.opsForSet().remove("user:tokens:" + username, token);
                            redisTemplate.delete("invalid:" + token);
                        }
                    } catch (Exception e) {
                        // 忽略单个token处理异常
                    }
                });
            }
        } catch (Exception e) {
            // 日志记录错误
        }
    }
}